package com.huawei.java.main;


import com.huawei.java.main.deployentity.Server;
import com.huawei.java.main.deployentity.Vm;
import com.huawei.java.main.inputentity.Require;
import com.huawei.java.main.inputentity.ServerType;

import java.util.*;

/**
 * 输出结果
 */
public class Output {
    /**
     *
     * @param currentDay 当前是第几天
     * @param startIndex 当天服务器的开始编号
     */
    public Output(int currentDay,int startIndex) {
        this.dailyAddRequireList =Input.dailyRequireList.get(currentDay).get("addList");
        this.currentDay=currentDay;
        this.startIndex=startIndex;
    }
    private int currentDay;
    private int startIndex;
    private List<Require> dailyAddRequireList;//当天对应的添加请求
    private final List<Vm> dailyVm = new ArrayList<>();//一天部署的虚拟机信息
    private final List<Server> dailyServer = new ArrayList<>();//一天购买的服务器信息

    public List<Vm> getDailyDeployVM() {
        return dailyVm;
    }

    public void addDailyDeployVM(Vm VM) {
        this.dailyVm.add(VM);
    }

    public List<Server> getDailyDeployServer() {
        return dailyServer;
    }

    public void addDailyDeployServer(Server server) {
        this.dailyServer.add(server);
    }

    public void result(){

        //1.统计购买了几种服务器
        dailyServer.sort(Comparator.comparing(ServerType::getServerType));//按照服务器类型排序
        Map<String,Integer> serverMap = new LinkedHashMap<>();
        for (Server server : dailyServer){
            server.setId(startIndex++);
            serverMap.put(server.getServerType(),findServerTypeNum(server.getServerType()));
        }
        System.out.printf("(purchase, %d)%n", serverMap.size());//买了几种类型的服务器

        //2.具体购买的服务器型号
        for (Map.Entry<String,Integer> obj: serverMap.entrySet()){
            System.out.printf("(%s, %d)%n", obj.getKey(), obj.getValue());
        }
        // TODO: 2021/3/16 记得考虑迁移如何实现
        //3.迁移。暂时不考虑迁移的事情
        System.out.println("(migration, 0)");

        //4.虚拟机部署。注意顺序！！！每天的请求和如何部署要一一对应，顺序不能乱
        for (Require require:dailyAddRequireList){
            Vm VM =findDeployNMByRequire(require);
            String node= VM.getNode();
            if (node.equals("AB"))
                System.out.printf("(%d)%n", VM.getDeployServer().getId());
            else
                System.out.printf("(%d, %s)%n", VM.getDeployServer().getId(), node);
        }
    }

    /**
     * 找到该类型的服务器类型购买了多少台
     * @param serverType
     * @return
     */
    int findServerTypeNum(String serverType){
        int sum=0;
        for (Server server : dailyServer){
            if (serverType.equals(server.getServerType()))
                sum++;
        }
        return sum;
    }

    /**
     * 通过请求寻找当天对应的部署虚拟机信息
     * 只需要在当天部署的服务器中寻找
     * @param require
     * @return
     */
    Vm findDeployNMByRequire(Require require){
        long vmId = require.getVmId();
        for (Vm VM : dailyVm){
            if (VM.getVmId()==vmId) return VM;
        }
        return null;
    }
}
